from django.http import JsonResponse
from django.views.generic import ListView, DetailView
from goods.models import GoodsType, IndexTypeGoodsBanner, IndexGoodsBanner, IndexPromotionBanner, GoodsSKU, \
    GoodComment


class GoodListView(ListView):
    model = IndexTypeGoodsBanner
    queryset = IndexTypeGoodsBanner.objects.all()
    template_name = 'goods/index.html'

    def get_context_data(self, *, object_list=None, **kwargs):
        type_list = GoodsType.objects.all()
        banner_list = IndexGoodsBanner.objects.all()
        promotion_list = IndexPromotionBanner.objects.all()
        content = {'type_list': type_list, 'banner_list': banner_list, 'promotion_list': promotion_list}
        return super().get_context_data(**content)


class GoodListByTypeView(ListView):
    template_name = 'goods/list.html'
    paginate_by = 5

    def get_queryset(self):
        good_list = GoodsSKU.objects.filter(type=self.kwargs.get('pk'))
        if self.request.GET.get("priceSore"):
            good_list = good_list.order_by("-price")
        if self.request.GET.get("salesSore"):
            good_list = good_list.order_by("-sales")
        return good_list

    def get_context_data(self, **kwargs):
        content = {
            'type_list': GoodsType.objects.all(),
            'type_good': GoodsType.objects.filter(pk=self.kwargs.get('pk')).first(),
        }
        return super().get_context_data(**content)


class GoodDetailView(DetailView):
    queryset = GoodsSKU.objects.all()
    template_name = 'goods/detail.html'


def comment_ajax(request):
    message = request.GET.get('message')
    good = request.GET.get("good_id")
    user = request.user
    if message == "":
        return False
    comment = GoodComment.objects.create(user_id=user, good_id_id=good, comment=message)
    json_str = comment.__dict__
    json_str.pop("_state")
    return JsonResponse(json_str)








